<?php
namespace Admin\Controller;
use Think\Controller;
class LoginController extends Controller 
{ 
    //验证码
    public function verify()
    {
       
      $Verify = new \Think\Verify();
      $Verify->fontSize = 25;
      $Verify->length   = 4;
      $Verify->entry();
    }
    
    public function index()
    {
      $this->display('login');
    }

       //登录验证
    public function dologin(){
      
        //接收数据验证码检测
        $code = I('post.verify');
        $Verify = new \Think\Verify();
        if(!$Verify->check($code))
        {
          $this->error('验证码错误',U('Login/index'));
        }

        //实例化
        $mod = M("admin");
        //自动验证
        $rules = array(
          array('admin_name','/\S+/','用户名必须填写！',1,'regex'),// // 验证是否为空或者空格回车
          array('password','/\S+/','密码必须填写！',1,'regex'),// // 验证是否为空或者空格回车

        );  
        if (!$mod->validate($rules)->create()){
           // 如果创建失败 表示验证没有通过 输出错误提示信息
           $this->error($mod->getError());
        }

        //用户名检测
        $arr['admin_name'] = I('post.admin_name');
        if(!$password = $mod->getFieldByAdmin_name($arr['admin_name'],'password'))
        {
          $this->error('用户名密码不正确',U('Login/index'));
        }
        
        //密码检测
        if($password !== md5(I('post.password')))
        {
          $this->error('用户名密码 不正确',U('Login/index'));
        }
        
        //判断是否禁用用户
        // dump(I('session.admin.status'));die;
        if($mod->getFieldByAdmin_name($arr['admin_name'],'status') == 0)
        {
            $this->error('用户被禁用，请更换用户登录',U('Login/index'));
        }

        // dump($admin_name);die;
        //获取ID
        $arr['id'] = $mod->getFieldByAdmin_name($arr['admin_name'],'id');
        //获取角色ID
        $arr['character_id'] = $mod->getFieldByAdmin_name($arr['admin_name'],'character_id');
        //存入session
        session('admin',$arr);
        //查询用户信息
        $character = M('admin a')->join('`character` c on c.id=a.character_id')->where('admin_name="'.session("admin.admin_name").'"')->getField('c.character');
            // dump($character);die;
            $this->assign('character',$character);
        // dump(session('admin'));die;
        $this->display('Index/index');
    }

    //退出当前用户
    public function logout()
    {
      session('admin',null);
      $this->redirect('Login/index');
    }
}